// pages/look-for-tech-params/look-for-tech-params.ts
import { getPublishList } from '../../../api/publish.js'
import { 
  PAGE_PRODUCT_DETAIL, 
  PAGE_BULK_MATERIAL_DETAIL, 
  goToPage 
} from '../../../config/pages.js'
import { formatSpecification } from '../../../utils/util'
import { formatDate } from '../../../utils/time'

Page({
  data: {
    // 搜索关键词
    searchKeyword: '',
    
    // 筛选条件
    selectedProvince: '',
    selectedCity: '',
    selectedDistrict: '',
    filterActive: false,
    
    // 分类筛选
    selectedType: '', // all, material, inventory
    
    // 搜索结果
    resultList: [] as any[],
    filteredCount: 0,
    
    // 加载状态
    loading: false,
    page: 1,
    limit: 20,
    hasMore: true,
    
    // 城市筛选弹窗
    showCityFilter: false,
    cityFilterValue: null as any,
  },

  onLoad(options: any) {
    console.log('技术参数查找页面加载完成', options);
    
    // 接收从 home 页面传递的搜索关键词
    if (options.keyword) {
      const keyword = decodeURIComponent(options.keyword);
      this.setData({
        searchKeyword: keyword
      });
      console.log('接收到的搜索关键词:', keyword);
    }
    
    this.loadSearchResults(true);
  },

  onShow() {
    console.log('技术参数查找页面显示');
  },

  // 加载搜索结果数据
  async loadSearchResults(refresh: boolean = false) {
    if (this.data.loading) return;
    
    if (refresh) {
      this.setData({
        page: 1,
        resultList: [],
        hasMore: true
      });
    }

    this.setData({ loading: true });

    try {
      const params: any = {
        page: this.data.page,
        limit: this.data.limit
      };

      // 添加筛选条件
      if (this.data.selectedProvince) {
        params.province = this.data.selectedProvince;
      }
      if (this.data.selectedCity) {
        params.city = this.data.selectedCity;
      }
      if (this.data.selectedDistrict) {
        params.district = this.data.selectedDistrict;
      }
      
      // 添加类型筛选
      if (this.data.selectedType && this.data.selectedType !== 'all') {
        params.type = this.data.selectedType;
      } else {
        // 默认只搜索材料和散料
        params.type = 'material,inventory';
      }
      
      // 添加搜索关键词
      if (this.data.searchKeyword) {
        params.keyword = this.data.searchKeyword;
      }

      console.log('搜索参数:', params);
      const res = await getPublishList(params);
      
      if (res.status === 200 && res.data) {
        // 格式化数据
        const formattedList = res.data.list.map((item: any) => ({
          ...item,
          spec: formatSpecification(item.spec || ''),
          formatted_date: formatDate(item.add_time || item.create_time),
          typeName: this.getTypeName(item.type),
          typeClass: this.getTypeClass(item.type)
        }));
        
        const newResults = refresh ? formattedList : [...this.data.resultList, ...formattedList];
        
        this.setData({
          resultList: newResults,
          filteredCount: res.data.count || newResults.length,
          hasMore: newResults.length < (res.data.count || 0),
          page: this.data.page + 1
        });
      }
    } catch (error) {
      console.error('加载搜索结果失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 获取类型名称
  getTypeName(type: string): string {
    const typeMap: any = {
      'material': '材料',
      'inventory': '散料'
    };
    return typeMap[type] || type;
  },

  // 获取类型样式类名
  getTypeClass(type: string): string {
    const classMap: any = {
      'material': 'material-item',
      'inventory': 'bulk-material-item'
    };
    return classMap[type] || 'material-item';
  },

  // 搜索输入处理
  onSearch(e: any) {
    const keyword = e.detail.value;
    console.log('搜索关键词:', keyword);
    this.setData({
      searchKeyword: keyword.trim()
    });
    this.loadSearchResults(true);
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      searchKeyword: ''
    });
    this.loadSearchResults(true);
  },

  // 筛选全国
  filterNational() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false
    });
    this.loadSearchResults(true);
  },

  // 显示城市选择弹窗
  showCityModal() {
    this.setData({
      showCityFilter: true,
      cityFilterValue: {
        province: this.data.selectedProvince,
        city: this.data.selectedCity,
        district: this.data.selectedDistrict
      }
    });
  },

  // 城市筛选确认
  onCityFilterConfirm(e: any) {
    const { address } = e.detail;
    console.log('选择的城市:', address);
    
    this.setData({
      selectedProvince: address.province || '',
      selectedCity: address.city || '',
      selectedDistrict: address.district || '',
      filterActive: true,
      showCityFilter: false
    });
    
    this.loadSearchResults(true);
  },

  // 城市筛选取消
  onCityFilterCancel() {
    this.setData({
      showCityFilter: false
    });
  },

  // 清除城市筛选
  onCityFilterClear() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false,
      showCityFilter: false
    });
    this.loadSearchResults(true);
  },

  // 选择全国
  onCityFilterNational() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false,
      showCityFilter: false
    });
    this.loadSearchResults(true);
  },

  // 显示类型筛选弹窗
  showTypeModal() {
    const types = ['全部分类', '材料', '散料'];
    wx.showActionSheet({
      itemList: types,
      success: (res) => {
        const typeValues = ['all', 'material', 'inventory'];
        this.setData({
          selectedType: typeValues[res.tapIndex]
        });
        this.loadSearchResults(true);
      }
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadSearchResults(true);
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadSearchResults();
    }
  },

  // 跳转到详情页
  goToDetail(e: any) {
    const id = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type;
    
    console.log('跳转到详情页:', { id, type });
    
    let pagePath = '';
    switch (type) {
      case 'material':
        pagePath = PAGE_PRODUCT_DETAIL;
        break;
      case 'inventory':
        pagePath = PAGE_BULK_MATERIAL_DETAIL;
        break;
      default:
        pagePath = PAGE_PRODUCT_DETAIL;
    }
    
    goToPage(pagePath, { id });
  }
});
